package cas.server.ldap.authe;

import org.ldaptive.BindOperation;
import org.ldaptive.BindRequest;
import org.ldaptive.Connection;
import org.ldaptive.LdapException;
import org.ldaptive.Response;
import org.ldaptive.ResultCode;
import org.ldaptive.auth.AuthenticationCriteria;
import org.ldaptive.auth.AuthenticationHandlerResponse;
import org.ldaptive.auth.PooledBindAuthenticationHandler;

/**
 * 由于有写导入的账号，已经加过密，这需要判断，是否将前台输入的密码使用同一种方式加密
 * 
 * @author Cre.Gu
 *
 */
public class SoaAuthenticationHandler extends PooledBindAuthenticationHandler {

	@Override
	protected AuthenticationHandlerResponse authenticateInternal(Connection c,
			AuthenticationCriteria criteria) throws LdapException {

		AuthenticationHandlerResponse response;
		final BindRequest request = new BindRequest(criteria.getDn(),
				criteria.getCredential());
		request.setSaslConfig(getAuthenticationSaslConfig());
		request.setControls(getAuthenticationControls());

		final BindOperation op = new BindOperation(c);
		try {
			final Response<Void> bindResponse = op.execute(request);
			response = new AuthenticationHandlerResponse(
					ResultCode.SUCCESS == bindResponse.getResultCode(),
					bindResponse.getResultCode(), c, bindResponse.getMessage(),
					bindResponse.getControls(), bindResponse.getMessageId());
		} catch (LdapException e) {
			if (ResultCode.INVALID_CREDENTIALS == e.getResultCode()) {
				response = new AuthenticationHandlerResponse(false,
						e.getResultCode(), c, e.getMessage(), e.getControls(),
						e.getMessageId());
			} else {
				throw e;
			}
		}
		return response;
	}

}
